using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability.API.APPLications.Commands.TraceabilityInfoshow;
using Traceability.API.Services;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.APPLications.CommandHanders.TraceabilityInfoshow
{
    /// <summary>
    /// 物理删除溯源信息命令处理程序（已改为物理删除）
    /// </summary>
    public class DeleteTraceabilityInfoCommandHandler : IRequestHandler<DeleteTraceabilityInfoCommand, APIResult<bool>>
    {
        private readonly IBaseRepository<TraceabilityInfo> _traceabilityRepository;
        private readonly TraceabilityRedisHelper _redisHelper;
        private readonly ILogger<DeleteTraceabilityInfoCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="traceabilityRepository">溯源信息仓储</param>
        /// <param name="redisHelper">Redis帮助类</param>
        /// <param name="logger">日志记录器</param>
        public DeleteTraceabilityInfoCommandHandler(
            IBaseRepository<TraceabilityInfo> traceabilityRepository,
            TraceabilityRedisHelper redisHelper,
            ILogger<DeleteTraceabilityInfoCommandHandler> logger = null)
        {
            _traceabilityRepository = traceabilityRepository;
            _redisHelper = redisHelper;
            _logger = logger;
        }

        /// <summary>
        /// 处理删除请求
        /// </summary>
        /// <param name="request">删除请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>删除结果</returns>
        public async Task<APIResult<bool>> Handle(DeleteTraceabilityInfoCommand request, CancellationToken cancellationToken)
        {
            APIResult<bool> result = new APIResult<bool>();

            // 开始数据库事务
            using var transaction = await _traceabilityRepository.Context.Database.BeginTransactionAsync(cancellationToken);

            try
            {
                _logger?.LogInformation("单个删除请求: ID={0}, DeleteBy={1}", request.TraceabilityId, request.DeleteBy);

                // 参数验证
                if (request.TraceabilityId <= 0)
                {
                    result.Code = APIEnum.操作失败;
                    result.Message = "无效的TraceabilityId";
                    return result;
                }

                // 查找要删除的记录
                var query = _traceabilityRepository.GetAll()
                    .Where(t => t.TraceabilityId == request.TraceabilityId);

                // 记录查询
                string sql = $"查询条件: TraceabilityId={request.TraceabilityId}";
                _logger?.LogInformation("单个物理删除SQL查询: {0}", sql);

                var traceability = await query.FirstOrDefaultAsync(cancellationToken);

                if (traceability == null)
                {
                    result.Code = APIEnum.查询失败;
                    result.Message = "记录不存在";
                    _logger?.LogWarning("尝试删除不存在的记录: ID={0}", request.TraceabilityId);
                    return result;
                }

                _logger?.LogInformation("找到要物理删除的溯源信息: {ProductionBatch}", traceability.ProductionBatch);

                // 物理删除
                var deleteResult = await _traceabilityRepository.Delete(traceability);

                _logger?.LogInformation("单个物理删除数据库操作结果: {0}", deleteResult);

                if (deleteResult <= 0)
                {
                    await transaction.RollbackAsync(cancellationToken);
                    result.Code = APIEnum.操作失败;
                    result.Message = "数据库物理删除失败";
                    return result;
                }

                // 提交数据库事务
                await transaction.CommitAsync(cancellationToken);
                _logger?.LogInformation("单个物理删除事务已提交: ID={0}", request.TraceabilityId);

                // 事务成功后从Redis缓存中移除
                try
                {
                    await _redisHelper.RemoveTraceabilityInfoAsync(request.TraceabilityId);
                    _logger?.LogInformation("单个物理删除Redis缓存移除成功: ID={0}", request.TraceabilityId);

                    // 清除列表缓存，以便下次获取最新数据
                    await _redisHelper.RemoveTraceabilityListAsync();
                }
                catch (Exception redisEx)
                {
                    // Redis操作失败不影响主要业务逻辑，只记录日志
                    _logger?.LogWarning(redisEx, "单个物理删除Redis缓存移除失败，但数据库操作已成功: ID={0}", request.TraceabilityId);
                }

                result.Code = APIEnum.删除成功;
                result.Message = "记录已成功物理删除";
                result.Data = true;
            }
            catch (Exception ex)
            {
                // 回滚事务
                try
                {
                    await transaction.RollbackAsync(cancellationToken);
                    _logger?.LogInformation("单个物理删除事务已回滚: ID={0}", request.TraceabilityId);
                }
                catch (Exception rollbackEx)
                {
                    _logger?.LogError(rollbackEx, "单个物理删除事务回滚失败: ID={0}", request.TraceabilityId);
                }

                _logger?.LogError(ex, "单个物理删除处理时发生异常: ID={0}", request.TraceabilityId);
                result.Code = APIEnum.操作失败;
                result.Message = $"物理删除失败: {ex.Message}";
                result.Data = false;
            }

            return result;
        }
    }
} 